﻿using Furion.DatabaseAccessor;
using Furion.JsonSerialization;
using Furion.Logging;

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Metadata.Internal;

using Project5.Core.Entities;

using System;
using System.Linq;
using System.Reflection.Emit;

namespace Project5.EntityFramework.Core
{
    [AppDbContext("Project5MSSql", DbProvider.SqlServer)]
    public class DefaultDbContext : AppDbContext<DefaultDbContext>, IModelBuilderFilter
    {
        public DefaultDbContext(DbContextOptions<DefaultDbContext> options) : base(options)
        {
        }

        public void OnCreating(ModelBuilder modelBuilder, EntityTypeBuilder entityBuilder, DbContext dbContext, Type dbContextLocator)
        {
            // 获取实体的所有属性，遍历
            var propertyInfos = entityBuilder.Metadata.ClrType.GetProperties();
            foreach (var propertyInfo in propertyInfos)
            {
                string propertyName = propertyInfo.Name;
                // 将 Guid 类型设置为 char(36)
                if (propertyInfo.PropertyType == typeof(Guid))
                {
                    entityBuilder.Property(propertyName).HasColumnType("char(36)");
                }
                else if (propertyInfo.PropertyType == typeof(Guid?))
                {
                    entityBuilder.Property(propertyName).HasColumnType("char(36)").IsRequired(false);
                }
            }
        }
    }
}